//
//  BaseListController.swift
//  edu
//
//  Created by karlzhou on 15/11/11.
//  Copyright © 2015年 karlzhou. All rights reserved.
//

import UIKit
import MJRefresh

class BaseListController<T>: UITableViewController {
    
    init(){
        super.init(style: .Plain)
    }
    
    var loadingView : UIActivityIndicatorView = UIActivityIndicatorView()
    var errorView :UIButton = UIButton()
    var emptyView : UIButton = UIButton()
    
    var dataSource: [T] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let header = MJRefreshNormalHeader{
            if(self.dataSource.count==0){
                self.loadingView.hidden = false
                self.loadingView.startAnimating()
            }else{
                self.loadingView.hidden = true
            }
            self.errorView.hidden=true
            self.emptyView.hidden=true
            self.loadData(APIClient.PAGE_FIRST)
        }
        
        header.lastUpdatedTimeLabel?.hidden = true
        header.stateLabel?.hidden = true
        let footer = MJRefreshAutoNormalFooter{
            () -> () in
            self.loadData(self.page())
        }
        
        footer.refreshingTitleHidden = true
        footer.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
        
        self.tableView.header=header
        self.tableView.footer=footer
        
        self.tableView.tableFooterView=UIView()
        
        let btnFrame: CGRect = CGRect(x: 0, y: 0, width: self.tableView.frame.width, height: self.tableView.frame.height)
        self.loadingView.frame = btnFrame
        self.loadingView.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
        
        self.emptyView.frame = btnFrame
        self.emptyView.setTitleColor(UIColor.grayColor(), forState: .Normal)
        self.emptyView.setTitle("空空如也~", forState: .Normal)
        
        self.errorView.frame = btnFrame
        self.errorView.setTitleColor(UIColor.grayColor(), forState: .Normal)
        self.errorView.setTitle("Error", forState: .Normal)
        
        self.view.addSubview(self.loadingView)
        self.view.addSubview(self.emptyView)
        self.view.addSubview(self.errorView)
        
        self.loadingView.hidden = true
        self.emptyView.hidden = true
        self.errorView.hidden = true
        
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func firstRefreshing(){
        
        self.loadingView.hidden = false
        self.loadingView.startAnimating()
        self.errorView.hidden=true
        self.emptyView.hidden=true
        delay(0.3, closure: {
            () -> () in
            self.loadData(self.page())
        })
        
    }
    
    func loadData(page: Int){
        delay(1.5) {
            self.endRefreshing()
        }
        
    }
    // MAKE: 默认进入下拉刷新状态，如需要进入上拉加载状态请使用self.tableView.footer.beginRefreshing()
    func beginRefreshing() {
        self.tableView.header.beginRefreshing()
    }
    
    // MAKE: 默认会结束下拉刷新及上拉加载刷新状态
    func endRefreshing() {
       
        if (self.tableView.header.isRefreshing()) {
            self.tableView.header.endRefreshing()
        }
        if (self.tableView.footer.isRefreshing()) {
            self.tableView.footer.endRefreshing()
        }
        // 通知MJRefresh是否未全部加载
        if (!self.hasMore()) {
            
            //self.tableView.footer.noticeNoMoreData()
        }
        if self.loadingView.isAnimating() {
            self.loadingView.stopAnimating()
        }
        if (self.dataSource.count == 0) {
            self.loadingView.hidden = true
            self.emptyView.hidden = false
            self.errorView.hidden = true
        } else {
            self.loadingView.hidden = true
            self.emptyView.hidden = true
            self.errorView.hidden = true
        }
    }
    
    
    // MAKE: 当前页码（按照TableView的数量计算）
    func page() -> Int {
        var count = self.tableView(self.tableView, numberOfRowsInSection: 0)
        count -= self.ignoreCount()
        if (count > 0) {
            let page = count / pageSize()
            // 如果默认page是从1开始的，则page+1
            if (APIClient.PAGE_FIRST == 1) {
                return page + 1
            }
            return page
        }
        return 0
    }
    
    // MAKE: 默认分页大小为ApiClient.PAGE_SIZE
    func pageSize() -> Int {
        return APIClient.PAGE_SIZE
    }
    
    // MAKE: 数据是否已经加载完毕
    func hasMore() -> Bool {
        var count = self.dataSource.count
        count -= self.ignoreCount()
        if (count % self.pageSize() != 0 || (count == 0)) {
            
            return false
        }
        return true
    }
    
    // MAKE: 忽略数（如果在头部插入了其他Cell，但又要保持分布正确，则添加相应的忽略数）
    func ignoreCount() -> Int {
        return 0
    }
    
}
